package com.itheima.health.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.common.RedisConst;
import com.itheima.health.dao.SetMealDao;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.SetMealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @author spt
 * @description 套餐SEVICE实现类
 * @date 2019/9/26
 **/
@Service
@Slf4j
public class SetMealServiceImpl implements SetMealService {
    @Autowired
    private SetMealDao setMealDao;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        log.info("[套餐-添加]data:{},checkgroupIds:{}", setmeal, checkgroupIds);
        // 调用DAO数据入库
        // 插入基本数据
        setMealDao.insert(setmeal);
        // 插入关联数据
        for (Integer checkgroupId : checkgroupIds) {
            setMealDao.insertSetMealAndCheckGroup(setmeal.getId(), checkgroupId);
        }
        //这里是数据库中保存的图片名，当我们添加一个套餐成功到数据库中时，说明这个图片不是垃圾图片，从redis中删除数据库中保存的图片
        redisTemplate.boundSetOps(RedisConst.SETMEAL_PIC_RESOURCES).remove(setmeal.getImg());
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //设置分页参数
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        //DAO查询数据
        Page<Setmeal> page = setMealDao.selectByCondition(queryPageBean.getQueryString());
        //封装返回值
        return new PageResult(page.getTotal(), page.getResult());
    }


    @Override
    public List<Setmeal> findAll() {
        return setMealDao.findAll();
    }

        /**
         * 根据图片名查询
         * @param img
         * @return
         */
        @Override
        public Long countByImg (String img){
            return setMealDao.countByImg(img);
        }

    @Override
    public Setmeal selectById(Integer id) {
        Setmeal byId = setMealDao.selectById(id);
        return byId;
    }

    /**
     * 获取套餐预约的占比(套餐名,套餐的预约数量)
     * @return
     */
    @Override
    public List<Map<String, Object>> getSetmealCount() {
        return  setMealDao.getSetmealCount();
    }
}
